{% extends 'baseadmin.html' %}

{% block title %}Markdown编辑器{% endblock %}

{% block styles %}
<script src="https://s4.zstatic.net/ajax/libs/vditor/3.10.7/index.min.js"></script>
<link rel="stylesheet" href="https://s4.zstatic.net/ajax/libs/vditor/3.10.7/index.min.css"/>
{% endblock %}

{% block maincontent %}
<div class="container mt-3">
    <div class="row">
        <div class="card mb-4">
            <div class="card-header">
                Markdown File | <button class="btn btn-outline-info" id="btnsave">Save File</button>
            </div>
            <div class="card-body">
                <p class="card-text"><div id="veditor" class="border rounded"></div></p>
            </div>
        </div>
    </div>
</div>

<script>
    // 通过fetch获取markdown文件内容
    var mdcont = "## 所见即所得（WYSIWYG）\n所见即所得模式对不熟悉 Markdown 的用户较为友好，熟悉 Markdown 的话也可以无缝使用。 ";
    var mymd;
    fetch("/static/markdown/2022-09-23-面试小工具.md")
        .then(response => response.text())
        .then(data => {
            mdcont = data;
            mymd = new Vditor('veditor', {
                "height": "100%",
                "width": "100%",
                "cache": {
                    "enable": false
                },
                "value": mdcont,
                "mode": "sv",
                "preview": {
                    "mode": "both"
                }
            });
        });

    // 保存文件
    document.getElementById("btnsave").addEventListener("click", function() {
        var newmdcont
        if (mymd == null) {
            alert("MD编辑器未加载完成，请稍后再试！");
            return;
        }else{
            var newmdcont = mymd.getValue();
        }
        
        /**
         * 前端使用javascript的fetch API发送POST请求, 请求头Content-Type: application/json, 请求体为json格式, 如下:
            {
                "filename": "文件名",
                "content": "文件内容"
            }
            JavaScript代码示例:
            fetch('/api/v1/fileapi/savemdfile', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    "filename": "文件名",
                    "content": "文件内容"
                })
            }).then(response => response.json()).then(data => {
                console.log(data);
            });
        */
        fetch('/api/v1/fileapi/savemdfile', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "filename": "2022-09-23-面试小工具-1.md",
                "content": newmdcont
            })
        }).then(response => response.json()).then(data => {
            console.log(data);
            if (data["status"] == "ok"){
                alert("文件保存成功！");
            }else{
                alert("文件保存--- 失败！");
            }
            
        });

    });
    
</script>
{% endblock %}